package vip.xiaonuo.tasks;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.Reactor;
import reactor.event.Event;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;
import vip.xiaonuo.facedoor.modular.visitor.constant.VisitorConstant;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.param.VisitorParam;
import vip.xiaonuo.facedoor.modular.visitor.service.FacedoorVisitorService;

import java.util.Date;
import java.util.List;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;

import javax.annotation.Resource;

@Component
@Slf4j
public class ExpiredVisitorTask implements TimerTaskRunner {


  private volatile boolean canRun = true;

  @Autowired
  private VisitorService visitorService;

  @Resource
  private Reactor reactor;

  @Autowired
  private FacedoorVisitorService facedoorVisitorService;

  @Override
  public void action(String taskId,String taskParam) {
    try {
      if (!canRun) {
        log.error("访客清理任务任务正在执行中，跳过本次执行！");
        return;
      }
      canRun = false;
      execute();
    } catch (Exception e) {
      log.error("访客清理任务正在执行错误【{}】", ExceptionUtils.getMessage(e));
      canRun = true;
    }
      canRun = true;
  }

  @XxlJob("ExpiredVisitorTask")
  private void execute() {
    List<Visitor> list = visitorService.list(new LambdaQueryWrapper<Visitor>().notIn(Visitor::getStatus, "0","4").le(Visitor::getVisitEndDate, new Date()));
    for (Visitor visitor : list) {
      try {
        if (VisitorConstant.EXAMINATION_PASSD.equals(visitor.getStatus())) {
          facedoorVisitorService.delete(new VisitorParam().setId(visitor.getId()));
          visitor.setStatus("0");
          visitorService.updateById(visitor);
        } else {
          visitor.setStatus("0");
          visitorService.updateById(visitor);
        }
        // 发布设备删除事件
        reactor.notify(EventTopic.VISITOR_DELETE, Event.wrap(visitor));
      } catch (Exception e) {
        log.error("清理人员发生错误【{}】", ExceptionUtils.getMessage(e));
      }
    }
  }

  @Override
  public void executeXxlJob() {

  }
}